<template>
  <el-upload
    class="upload-box"
    action
    :auto-upload="false"
    :show-file-list="false"
    :accept="accept"
    :file-list="[]"
    list-type="picture"
    :limit="1"
    :key="timeStamp"
    :multiple="false"
    :before-upload="beforeUpload"
    :on-change="handleChange">
    <div class="img-box">
      <img v-if="imgUrl" :src="imgUrl" alt="">
      <i class="el-icon-plus" v-else></i>
    </div>
  </el-upload>
</template>

<script>
export default {
  data() {
    return {
      timeStamp: Date.now(),
      imgUrl: null,
      accept: '.jpg, .png, .jpeg, .JPG, .PNG, .JPEG'
    };
  },
  methods: {
    async beforeUpload(file) {
      return new Promise((resolve, reject) => {
        const fileType = file.type.replace('image/', '.');
        const isImage = this.accept.indexOf(fileType) > -1;
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isImage) {
          this.$message.error('上传头像只能是 jpg、png、jpeg 格式!');
          reject(false);
        }
        if (!isLt10M) {
          this.$message.error('上传头像图片大小不能超过 10MB!');
          reject(false);
        }
        resolve(true);
      });
    },
    handleChange(file) {
      this.beforeUpload(file.raw)
      .then(() => {
        this.imgUrl = file.url;
        let imgObj = {
          url: file.url,
          file
        };
        this.$emit('setImg', imgObj);
      }).catch(() => {
        this.timeStamp = Date.now();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.upload-box {
  width: 100%;
  height: 100%;
  & > ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    .img-box {
      width: 100%;
      height: 100%;
      display: flex;
      img {
        max-width: 100%;
        max-height: 100%;
        margin: auto;
      }
      i {
        margin: auto;
        &::before {
          font-size: 50px;
          color: #fff;
        }
      }
    }
    .el-upload__input {
      display: none;
    }
  }
}
</style>
